from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.fields import GenericRelation
from django.urls import reverse

from ckeditor_uploader.fields import RichTextUploadingField
from mdeditor.fields import MDTextField
from read_record.models import ReadNum, ReadNumExpand, ReadDetail


# Create your models here.

class BlogType(models.Model):
    type_name = models.CharField(max_length=15)

    def __str__(self):
        return self.type_name

class Blog(models.Model, ReadNumExpand):
    title = models.CharField(max_length=50)
    blog_type = models.ForeignKey(BlogType, on_delete=models.CASCADE)
    content = MDTextField()
    author = models.ForeignKey(User, on_delete=models.CASCADE, limit_choices_to={'is_superuser':True})  # 作者只能是超级用户
    create_time = models.DateTimeField(auto_now_add=True)
    last_updated_time = models.DateTimeField(auto_now=True)
    read_detail = GenericRelation(ReadDetail)

    def get_url(self):
       return reverse('blog_detail', kwargs={'blog_pk': self.pk})

    def __str__(self):
        return '<blog>:{}'.format(self.title)
    
    class Meta:
        ordering = ['-create_time']
